package by.yativem.commons.thread;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

public class ThreadPool {
	private static final Logger log = Logger.getLogger(ThreadPool.class);	
	List<ThreadWorker> workers;
	private int threadCapacity = 100;
	private static int lastWorkerId =0;
	
	
	public ThreadPool(int pullCount) {
		threadCapacity = pullCount;
		workers = new ArrayList<ThreadWorker>(pullCount);
	}
	
	
	
	/*
	 * Running the r on new Thread if the ;
	 */
	public synchronized boolean processThread(Runnable r){
		ThreadWorker w = getAvaliableWorker();
		if(w == null){
			return false;
		}		
		w.processThread(r);
		return true;
	}
	
	public synchronized boolean hasAvaliableWorker(){
		for(ThreadWorker w : workers){
			if( !w.isRunning() ){
				return true;
			}
		}
		if(workers.size() < threadCapacity){
			
			return true;
		}
		return false;
	}
	
	private ThreadWorker getAvaliableWorker(){
		for(ThreadWorker w : workers){
			if( !w.isRunning() ){
				return w;
			}
		}
		if(workers.size() < threadCapacity){
			ThreadWorker w  =new ThreadWorker(generateNextWorkerId());
			workers.add(w);
			w.start();
			return w;
		}
		return null;
	}
	
	private synchronized int generateNextWorkerId(){
		return lastWorkerId++;
	}
}
